<?php

namespace Home\Controller;

use Org\Net\Http;
use Think\Image;
use Think\Page;
use Think\Controller;

class AccountController extends Controller {
	/**
	 * 修改签名
	 */
	public function signature() {
		if (IS_POST) {
			// file_put_contents("Public/Log/log.txt", "post:".json_encode($_POST)."\r\n",FILE_APPEND|LOCK_EX);
			$account = D ( 'Account' );
			$data ['signature'] = $_POST ['signature'];
			$where ['id'] = $_POST ['account_id'];
			$result = $account->where ( $where )->save ( $data );
			if ($result) {
				$json ['result'] = 0;
				$json ['msg'] = '修改成功';
			} else {
				$json ['result'] = - 1;
				$json ['msg'] = '修改失败';
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 修改头像
	 */
	public function changeHeadimg() {
		if (IS_POST) {
			$file = $_FILES ['image'];
			if (sizeof ( $file ) > 0) {
				$path = "Public/Upload/HeadImage/";
				$util = A ( "Util" );
				$util->createDir ( $path );
				$path_info = pathinfo ( $file ['name'] );
				$file_extension = $path_info ["extension"];
				$file_name = uniqid ( "head_" ) . "." . $file_extension;
				$path_name = $path . $file_name;
				$image->open ( $file ['tmp_name'] );
				$image->save ( $path_name );
				$data ['headimgurl'] = 'http://' . $_SERVER ['HTTP_HOST'] . '/' . __ROOT__ . '/' . $path_name;
				$result = M ( "Account" )->where ( array (
						'id' => $_POST ['id'] 
				) )->save ( $data );
				if ($result) {
					$json ['result'] = 0;
					$json ['msg'] = '修改成功';
				} else {
					$json ['result'] = - 1;
					$json ['msg'] = '修改失败';
				}
				$this->ajaxReturn ( $json );
			}
		}
	}
	/**
	 * 获取用户信息
	 */
	public function getAccountById() {
		if (IS_POST) {
			// file_put_contents("Public/Log/log.txt", "post:".json_encode($_POST)."\r\n",FILE_APPEND|LOCK_EX);
			$account = D ( 'Account' );
			$where ['id'] = $_POST ['account_id'];
			$arr = $account->where ( $where )->field ( "id,nickname,headimgurl" )->find ();
			if ($arr) {
				$json ['result'] = 0;
				$json ['msg'] = '成功';
				$json ['account'] = $arr;
			} else {
				$json ['result'] = - 1;
				$json ['msg'] = '无此用户信息';
			}
			// file_put_contents("Public/Log/log.txt", "json:".json_encode($json)."\r\n",FILE_APPEND|LOCK_EX);
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 单局数据结算
	 */
	public function currentData() {
		if (IS_POST) {
			$aid = I ( 'id' );
			$data ['aid'] = $aid;
			$data ['time'] = I ( 'time' );
			$data ['credit'] = I ( 'credit' );
			$time = D('Time');
			$data = $time->create($data);
			if($data){
				//每局记录
				$time->add($data);
			}
			
			$list = $time->where(array('aid'=>$aid))->field("SUM(credit) as integral,MAX(credit) as gameCredits,MAX(time) as maxTime")->find();
			$account = D('Account');
			$where['id'] = $data ['aid'];
			$account->where($where)->save($list);
			$json = $list;
			$json['result'] = 0 ;
			$json['msg'] = "成功" ;
			$this->ajaxReturn($json);
		}
	}
	/**
	 * 第三方登录
	 */
	public function thirdLogin() {
		// file_put_contents("Public/Log/log.txt", "post:".json_encode($_POST)."\r\n",FILE_APPEND|LOCK_EX);
		if (IS_POST) {
			$account = D ( 'Account' );
			$types = array (
					'wx',
					'qq',
					'wb' 
			);
			$type = $_POST ['type'];
			if (in_array_case ( $type, $types )) {
				switch ($type) {
					case 'wx' :
						$unionid = $_POST ['unionid'];
						break;
					case 'qq' :
						$unionid = md5 ( $_POST ['headimgurl'] );
						break;
					case 'wb' :
						$unionid = $_POST ['unionid'];
						break;
				}
				
				$where ["{$type}_id"] = $unionid;
				$result = $account->where ( $where )->field ( "id,nickname,gender,headimgurl,birthday,signature,phone,email" )->find ();
				// vendor ( "rongcloud.ServerAPI" );
				// $api = new \ServerAPI ();
				
				if ($result) {
					$json ['result'] = 0;
					$json ['msg'] = '登录成功';
					
					// $back = json_decode ( $api->getToken ( $result ['id'], $result ['nickname'], $result ['headimgurl'] ), 'json' );
					// $result ['token'] = $back ['token'];
					$json ['account'] = $result;
				} else {
					$util = A ( 'Util' );
					$data ['id'] = 'A' . $util->getId (); // 生成用户ID
					$data ["{$type}_id"] = $unionid;
					$data ['gender'] = $_POST ['gender'];
					$data ['nickname'] = $_POST ['nickname'];
					$data ['headimgurl'] = $_POST ['headimgurl'];
					$result = $account->add ( $data );
					$json ['result'] = 0;
					$json ['msg'] = '登录成功';
					
					// $back = json_decode ( $api->getToken ( $data ['id'], $data ['nickname'], $data ['headimgurl'] ), 'json' );
					// $data ['token'] = $back ['token'];
					
					$data ['birthday'] = "1990-01-01";
					$data ['signature'] = '';
					$json ['account'] = $data;
				}
			} else {
				$json ['result'] = - 1;
				$json ['msg'] = '不支持改方式登录';
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 用户注册
	 */
	public function register() {
		if (IS_POST) {
			$account = D ( "Account" );
			$data = $account->create ( $_POST );
			// 验证是否已经注册过
			if ($data) {
				$http = new Http ();
				$post ['latitude'] = $_POST ['latitude'];
				$post ['longitude'] = $_POST ['longitude'];
				$post ['geotable_id'] = C ( "BAIDU_AVENGERS" );
				$post ['ak'] = C ( "BAIDU_AK" );
				$post ['coord_type'] = 1;
				$post ['title'] = $_POST ['nickname'];
				$post ['tags'] = $_POST ['phone'];
				$data ['post'] = $post;
				$back = $http->fsockopenDownload ( C ( "BAIDU_POI_CREATE" ), $data );
				$back = json_decode ( $back, 'json' );
				// 添加百度位置是否成功
				if ($back ['status'] == 0) {
					$data ['pid'] = $back ['id'];
					$url = C ( 'BAIDU_POI_detail' ) . "?id={$back['id']}&geotable_id={$post ['geotable_id']}&ak={$post ['ak']}";
					file_put_contents ( "Public/Log/log.txt", "url:" . $url . "\r\n", FILE_APPEND | LOCK_EX );
					$back = $http->fsockopenDownload ( $url );
					$back = json_decode ( $back, 'json' );
					// 获取百度位置是否成功
					if ($back ['status'] == 0) {
						$poi = $back ['poi'];
						if ($poi ['province'] == $poi ['city']) {
							$region = $poi ['province'];
						} else {
							$region = $poi ['province'] . $poi ['city'];
						}
						$data['province'] = $poi ['province'];
						$data['city'] = $poi ['city'];
						$result = $account->add ( $data );
						// 添加数据是否成功
						if ($result) {
							$json ['result'] = 0;
							$json ['msg'] = "注册成功";
							$json ['region'] = $region;
						} else {
							$json ['result'] = - 1;
							$json ['msg'] = "注册失败";
						}
					}else{
						$json ['result'] = - 4;
						$json ['msg'] = "获取位置失败";
					}
				}else{
					$json ['result'] = - 3;
					$result = $account->add ( $data );
					$json ['msg'] = "添加位置失败";
				}
			} else {
				$json ['result'] = - 2;
				$json ['msg'] = $account->getError ();
			}
			// file_put_contents ( "Public/Log/log.txt", "json:" . json_encode ( $data ) . "\r\n", FILE_APPEND | LOCK_EX );
			$this->ajaxReturn ( $json );
		} else {
			$this->display ();
		}
	}
	/**
	 * 用户登录
	 */
	public function login() {
		if (IS_POST) {
			$where ['phone'] = $_POST ['phone'];
			$account = D ( 'Account' );
			file_put_contents ( "Public/Log/log.txt", "post:" .json_encode($_POST). "\r\n", FILE_APPEND | LOCK_EX );
			$arr = $account->where ( $where )->field ( "id,password,nickname,gender,headimgurl,birthday,signature,phone,email,pid" )->find ();
			//是否存在账号
			if ($arr) {
				//验证密码是否正确
				if ($arr ['password'] == md5 ( $_POST ['password'] )) {
					$http = new Http ();
					$post ['latitude'] = $_POST ['latitude'];
					$post ['longitude'] = $_POST ['longitude'];
					$post ['geotable_id'] = C ( "BAIDU_AVENGERS" );
					$post ['ak'] = C ( "BAIDU_AK" );
					$post ['coord_type'] = 1;
					$data ['post'] = $post;
					if($arr ['pid'] == null){
						$data ['post'] ['title'] = $arr ['nickname'];
						$data ['post'] ['tags'] = $arr ['phone'];
						$back = $http->fsockopenDownload ( C ( "BAIDU_POI_CREATE" ), $data );
					}else{
						$data ['post'] ['id'] = $arr ['pid'];
						$back = $http->fsockopenDownload ( C ( "BAIDU_POI_UPDATE" ), $data );
					}
					file_put_contents ( "Public/Log/log.txt", "data:" .json_encode($data). "\r\n", FILE_APPEND | LOCK_EX );
					$back = json_decode ( $back, 'json' );
					//修改位置是否成功
					if ($back ['status'] == 0) {
						$pid = $back ['id'];
						$url = C ( 'BAIDU_POI_detail' ) . "?id={$pid}&geotable_id={$post ['geotable_id']}&ak={$post ['ak']}";
						$back = $http->fsockopenDownload ( $url );
// 						file_put_contents ( "Public/Log/log.txt", "back:" .$back. "\r\n", FILE_APPEND | LOCK_EX );
						$back = json_decode ( $back, 'json' );
						//获取位置信息
						if ($back ['status'] == 0) {
							$poi = $back ['poi'];
							if ($poi ['province'] == $poi ['city']) {
								$region = $poi ['province'];
							} else {
								$region = $poi ['province'] . $poi ['city'];
							}
							$where2['id'] = $arr['id'];
							$data2['province'] = $poi ['province'];
							$data2['city'] = $poi ['city'];
							$data2['pid'] = $pid;
							//修改用户的位置信息
							$account->where($where2)->save($data2);
							$arr['region'] = $region;
							$json ['result'] = 0;
							$json ['account'] = $arr;
							$json ['msg'] = "登录成功";
						}
					}else{
						$json ['result'] = - 3;
						$json ['account'] = $arr;
						$json ['msg'] = "修改位置失败";
					}
				} else {
					$json ['result'] = - 1;
					$json ['msg'] = "密码错误";
				}
			} else {
				$json ['result'] = - 2;
				$json ['msg'] = "账号不存在";
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 重置密码
	 */
	public function resetPassword() {
		if (IS_POST) {
			$old = $_POST ['oldPwd'];
			$userid = $_POST ['id'];
			$new = $_POST ['newPwd'];
			$account = D ( 'Account' );
			if (md5 ( $old ) == $account->where ( array (
					'id' => $userid 
			) )->getField ( 'password' )) {
				$result = $account->where ( array (
						'id' => $userid 
				) )->setField ( 'password', md5 ( $new ) );
				if ($result) {
					$json ['msg'] = "密码已经成功修改！";
					$json ['result'] = 0;
					$this->ajaxReturn ( $json );
				} else {
					$json ['msg'] = "密码修改失败！";
					$json ['result'] = - 2;
					$this->ajaxReturn ( $json );
				}
			} else {
				$json ['msg'] = "旧密码错误，无法修改！";
				$json ['result'] = - 3;
				$this->ajaxReturn ( $json );
			}
		} else {
			$json ['msg'] = "数据不是以post方式提交";
			$json ['result'] = - 1;
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 验证手机号是否已经注册
	 */
	public function getVerify() {
		// file_put_contents("Public/Log/log.txt", "post:".json_encode($_POST)."\r\n",FILE_APPEND|LOCK_EX);
		if (IS_POST) {
			// file_put_contents("Public/Log/log.txt", "post:".json_encode($_POST)."\r\n",FILE_APPEND|LOCK_EX);
			$phone = trim ( $_POST ['phone'] );
			if (preg_match ( "/^1(3[0-9]|5[0-9]|8[0-9])\\d{8}$/", $phone )) {
				// 验证通过,先通过短信接口发给用户短信，然后再传验证码给app
				if (M ( 'account' )->where ( array (
						'phone' => $phone 
				) )->find ()) {
					$this->ajaxReturn ( array (
							'result' => - 3,
							'msg' => '该手机号码已经注册过了' 
					) );
				}
				$this->ajaxReturn ( array (
						'result' => 0,
						'msg' => '手机号码通过验证' 
				) );
			} else {
				// 手机号码格式不对
				$this->ajaxReturn ( array (
						'result' => - 1,
						'msg' => '手机号码格式不正确' 
				) );
			}
		}
		$this->ajaxReturn ( array (
				'result' => - 2,
				'msg' => '数据不是以POST方式提交' 
		) );
	}
	/**
	 * 修改用户信息
	 */
	public function updateInfo() {
		if (IS_POST) {
			$data = $_POST;
			$result = M ( "Account" )->where ( array (
					'id' => $_POST ['id'] 
			) )->save ( $data );
			if ($result) {
				$json ['result'] = 0;
				$json ['msg'] = '修改成功';
			} else {
				$json ['result'] = - 1;
				$json ['msg'] = '修改失败';
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 积分变更
	 */
	public function updateIntegral() {
		if (IS_POST) {
			$where ['id'] = I ( 'id' );
			// $data['integral'] = I('integral');
			// $integral = I('integral');
			$account = D ( 'Account' );
			$res = $account->where ( $where )->find ();
			$data ['integral'] = $res ['integral'] + I ( 'integral' );
			$result = $account->where ( $where )->save ( $data );
			if ($result) {
				$json ['result'] = 0;
				$json ['msg'] = '变更成功';
			} else {
				$json ['result'] = - 1;
				$json ['msg'] = '变更失败';
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 最高游戏积分更新
	 */
	public function updateCredits() {
		if (IS_POST) {
			$where ['id'] = I ( 'id' );
			$account = D ( 'Account' );
			$res = $account->where ( $where )->find ();
			$gameCredits = I ( 'gameCredits' );
			if ($gameCredits > $res ['gameCredits']) {
				$data ['gameCredits'] = $gameCredits;
				$result = $account->where ( $where )->save ( $data );
				if ($result) {
					$json ['result'] = 0;
					$json ['msg'] = '用户最高记录更新';
				} else {
					$json ['result'] = - 1;
					$json ['msg'] = '用户最高记录更新失败';
				}
			} else {
				$json ['result'] = - 2;
				$json ['msg'] = '未打破用户最高记录';
			}
			$this->ajaxReturn ( $json );
		}
	}
	/**
	 * 排行榜
	 */
	public function Ranklist() {
		$id = I ( 'id' );
		$account = D ( 'Account' );
		$acc = $account->where ( array (
				'id' => $id 
		) )->field ( "nickname,headimgurl,gameCredits" )->find ();
		$where ['gameCredits'] = array (
				'gt',
				$acc ['gamecredits'] 
		);
		// 获取该用户的排名(即比该用户分数高的人数+1)
		$ranking = $account->where ( $where )->field("count(*) as ranking")->find ();
		$ranking = $ranking['ranking']+ 1;
		$result = $account->limit ( 10 )->order ( 'gameCredits desc' )->field ( "nickname,headimgurl,gameCredits" )->select ();
		if ($result) {
			$json ['result'] = 0;
			$json ['msg'] = '查询成功';
			$json ['ranking'] = $ranking;
			if ($ranking > 10) {
				$json ['account'] = $acc;
			}else{
				if($result[9]['gamecredits'] <= $acc ['gamecredits']){
					array_splice($result, $ranking-1,0,array($acc));
					$count = count($result);
					for($i = $ranking;$i<$count;$i++){
						$item = $result[$i];
						if($item['nickname']==$acc['nickname']){
							array_splice($result, $i, 1); 
							break;
						}
					}
				}
			}
			$json ['ranklist'] = $result;
		} else {
			$json ['result'] = - 1;
			$json ['msg'] = '查询失败';
		}
		$this->ajaxReturn ( $json );
	}
}